package com.huxiu.yd;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.google.gson.Gson;
import com.huxiu.yd.net.GsonRequest;
import com.huxiu.yd.net.NetworkConstants;
import com.huxiu.yd.net.UploadImageRequest;
import com.huxiu.yd.net.responses.BaseResponse;
import com.huxiu.yd.utils.Global;
import com.huxiu.yd.utils.ImageUtils;
import com.huxiu.yd.utils.Settings;
import com.huxiu.yd.utils.Utils;
import com.makeramen.roundedimageview.RoundedImageView;
import com.nostra13.universalimageloader.core.ImageLoader;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import butterknife.ButterKnife;
import butterknife.InjectView;

/**
 * Created by yao on 15/8/29:下午9:28.
 */
public class ViewProfileActivity extends BaseActivity implements OnClickListener, TextWatcher, UploadImageRequest.ResultListener {

    @InjectView(R.id.back)
    ImageView back;

    @InjectView(R.id.left_text)
    TextView leftText;

    @InjectView(R.id.title)
    TextView title;

    @InjectView(R.id.right_image)
    ImageView rightImage;

    @InjectView(R.id.right_text)
    TextView rightText;

    @InjectView(R.id.avatar)
    RoundedImageView avatar;

    @InjectView(R.id.yijuhua)
    EditText yijuhua;

    @InjectView(R.id.textcount)
    TextView textcount;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view_profile);
        ButterKnife.inject(this);
        back.setOnClickListener(this);
        leftText.setVisibility(View.GONE);
        rightText.setVisibility(View.VISIBLE);
        rightText.setText(R.string.save);
        rightText.setOnClickListener(this);
        rightText.setTextColor(getResources().getColor(R.color.white));
        title.setText(R.string.modify_profile);
        avatar.setOnClickListener(this);
        yijuhua.setText(Global.user.yijuhua);
        yijuhua.addTextChangedListener(this);
        textcount.setText(Global.user.yijuhua.length() + "/30");
        ImageLoader.getInstance()
                .displayImage(Global.user.avatar, avatar, ImageUtils.getAvatarDisplayOption());
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.avatar:
                ImageUtils.takeOrChoosePhoto(this, ImageUtils.TAKE_OR_CHOOSE_PHOTO);
                break;
            case R.id.right_text:
                submitSignature();
                break;
        }
    }

    private void submitSignature() {
        String url = NetworkConstants.MEMBER_URL;
        Map<String, String> params = new HashMap<>();
        params.put("act", "up_user_info");
        params.put("yijuhua", yijuhua.getText().toString());
        GsonRequest<BaseResponse> request = new GsonRequest<>(url, Request.Method.POST, BaseResponse.class,
                true, params, new Response.Listener<BaseResponse>() {
            @Override
            public void onResponse(BaseResponse response) {
                if (response.isSuccess()) {
                    Utils.showToast(R.string.submit_signature_success);
                    Settings.saveSignature(yijuhua.getText().toString());
                    Global.user.yijuhua = yijuhua.getText().toString();
                    Settings.saveProfile(new Gson().toJson(Global.user));
                    finish();
                } else {
                    Utils.showToast(response.msg);
                }
            }
        }, mErrorListener);
        showProgress();
        mQueue.add(request);
//        mQueue.start();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case ImageUtils.TAKE_OR_CHOOSE_PHOTO:
                File f = ImageUtils.getPhotoFromResult(this, data);
                ImageUtils.doCropAvatarPhoto(this, f);
                return;
            case ImageUtils.PHOTO_PICKED_WITH_DATA: {
                Bitmap bitmap = ImageUtils.getCroppedImage();
                if (bitmap == null) {
                    return;
                }
                new UploadImageRequest(this, NetworkConstants.MEMBER_URL, null, bitmap, this).execute();
            }
            break;
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        textcount.setText(s.length() + "/30");
    }

    @Override
    public void onSuccess(String msg) {
        try {
            JSONObject json = new JSONObject(msg);
            JSONObject data = json.getJSONObject("data");
            String avatar = data.getString("avatar");
            Global.user.avatar = avatar;
            Settings.saveProfile(new Gson().toJson(Global.user));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        ImageLoader.getInstance()
                .displayImage(Global.user.avatar, avatar, ImageUtils.getAvatarDisplayOption());
    }

    @Override
    public void onFailure(String msg) {
        if (TextUtils.isEmpty(msg)) {
            msg = getString(R.string.generic_failure);
            Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
        }
    }
}
